# -*- coding=utf-8

import logging
import os
import sys
from pprint import pprint

from qcloud_cos import CosConfig, CosServiceError
from qcloud_cos import CosS3Client
from qcloud_cos.cos_threadpool import SimpleThreadPool

# 正常情况日志级别使用 INFO，需要定位时可以修改为 DEBUG，此时 SDK 会打印和服务端的通信信息
logging.basicConfig(level=logging.INFO, stream=sys.stdout)

# 1. 设置用户属性, 包括 secret_id, secret_key, region等。Appid 已在 CosConfig 中移除，请在参数 Bucket 中带上 Appid。Bucket 由 BucketName-Appid 组成
secret_id = 'AKIDyyFnIm7NYzLdq1ACINNBCNRQKDB3t6Xz'  # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = 'lxHgE7ydAoOrPSWes7LUbp3JXj5d9bu8'  # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
bucket = 'context-1257245862'

# secret_id = 'AKIDoY8VgQZ3we9RceATIwPfidOyMbeVr5pO'  # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
# secret_key = 'TkqmZDgpqfVr8HF1aw9AyiGwVs57xa5R'  # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
# bucket = 'demo-1251808174'
# queue_id = 'p75e7d74b6ef14ae5936b380fcd9ec4ff'

region = 'ap-chengdu'  # 替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
# COS 支持的所有 region 列表参见 https://cloud.tencent.com/document/product/436/6224
# token = '6jmwo5E6ibUgBjQZRajnwmNNv2HW59ba88615ed1bca62a27320efa548b14320bEcSKHQlM_7imF128QIzcxC_bggVEw9t8d4zl6tbk8YgNBv1--wwHm6BVQp3B1ziAHSdXtdzJp9cqZU3XjK44PX1fd1e7j3CbCEdQKCfvVUMj6uFxhCaWYLFUC0ZwTvTcm8-4zGie1l2F5Q9V5Aepb4RRIf12kg-KD6mtgA8AaWOBnjREvoxhv1mzgX3LtZ2GPxa8Dn6o_LnKmLwUUA-6M57FqBh4kt3rxNtTbkJExYRHCxhJNTG9tXxwnw2m9AI6JVQsKiEPZILW8-KqmOIdr3VSHtpRIywoOOMfsLHK-Y5V1kSlFuh3hivP7Y_Nnj44OrhatuPTI0Pf7nBZh_1B4dBNrMR2JNLA4AbhDMikpqaCRPm9nJB5HjUjU6fK82XrLKUr_dm9cBAdvko141oo_c8y-o1F0JdBCplwUSynh-4FHE9VZIdBJxB08WHmHBkWeuBU5YFwC48Q1kH7j4kOd8h2OTtH63EA9dEwwclO4rkzUW7TOUGzQhy_QL4oiyf3ZltOP7alj1mND9zrEGvUGIQdFxj5uzUQelMfHoLUi5HvMGhCpU2mnGY4OJnKbJE-nSC8jsboOpA_5DG4o8XDa6FfuLKyKiV1YcSGuLpx33WET0XRR4dOUPQQYrQ-O_dC3TARB-ohPHJZnvYyjt4XAFJwuqM_M2TjFM5plTVVBb-Op9Ylin0WlwcAPWjDXkRdQ_i6EBlHb6l7vOtmFx_wehU_THaScUc1waHC8Gr7OZs'               # 如果使用永久密钥不需要填入 token，如果使用临时密钥需要填入，临时密钥生成和使用指引参见 https://cloud.tencent.com/document/product/436/14048
token = None
scheme = 'https'  # 指定使用 http/https 协议来访问 COS，默认为 https，可不填

config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key, Token=token, Scheme=scheme)
client = CosS3Client(config)
#
# response = client.list_buckets()
# print('buckets:', response)


# media/edoc/common/2024-05/-44640109/page_2_6.pdf

def update():
    # 高级上传接口（推荐）
    # # 根据文件大小自动选择简单上传或分块上传，分块上传具备断点续传功能。
    response = client.upload_file(
        Bucket=bucket,
        LocalFilePath='abc.edoc',
        Key='/tmp/edoc/2024-10/test/abc.zip',
        PartSize=1,
        MAXThread=10,
        EnableMD5=False
    )
    print('------------------', response['ETag'])
#
#
# def many_update():
#     uploadDir = './img'
#     g = os.walk(uploadDir)
#     # 创建上传的线程池
#     pool = SimpleThreadPool()
#     for path, dir_list, file_list in g:
#         for file_name in file_list:
#             srcKey = os.path.join(path, file_name)
#             cosObjectKey = srcKey.strip('/')
#             # 判断 COS 上文件是否存在
#             exists = False
#             try:
#                 response = client.head_object(Bucket=bucket, Key=cosObjectKey)
#                 exists = True
#             except CosServiceError as e:
#                 if e.get_status_code() == 404:
#                     exists = False
#                 else:
#                     print("Error happened, reupload it.")
#             if not exists:
#                 print("File %s not exists in cos, upload it", srcKey)
#                 pool.add_task(client.upload_file, bucket, cosObjectKey, srcKey)
#
#     pool.wait_completion()
#     result = pool.get_result()
#     if not result['success_all']:
#         print("Not all files upload successed. you should retry")
#
#
# update()
# body = {
#     'Prefix': 'media/edoc/common/aaa',
#     # 'UnCompressKey': base64.b64encode("123456".encode("utf-8")).decode('utf-8'),
#     'PrefixReplaced': '0'
# }
# #
# image_params = f'imageMogr2/format/webp|imageMogr2/quality/50|imageMogr2/resharp/50'
# resp = client.ci_create_doc_job(
#     Bucket=bucket,
#     QueueId=queue_id,
#     InputObject='media/edoc/common/2024-07/-47489614/历史假日时光暑假总动员八升九题干1.pdf',
#     OutputBucket=bucket,
#     OutputRegion=region,
#     OutputObject=f'media/edoc/course/2024-07/3017/img_${{Number}}.webp',
#     TgtType='jpg',
#     # PaperDirection=1,
#     # PaperSize=self.paper_size,
#     ImageParams=image_params
# )
# job = resp.get('JobsDetail')
# print('job', job)

resp = client.ci_get_doc_job(
    Bucket=bucket,
    JobID='58967cc63e5fcbf6c629a879f64958cb-2'
)
pprint(resp)

